package com.carlos.gateway.security.handler;

import com.alibaba.fastjson.JSON;
import com.carlos.gateway.vo.ResultCode;
import com.carlos.gateway.vo.ResultVO;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.http.MediaType;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.web.server.WebFilterExchange;
import org.springframework.security.web.server.authentication.ServerAuthenticationFailureHandler;
import org.springframework.stereotype.Component;
import reactor.core.publisher.Mono;

import java.nio.charset.StandardCharsets;

/**
 * @author 李健成
 * @date 2021/10/28
 */

@Component
public class JsonAuthenticationFailureHandler implements ServerAuthenticationFailureHandler {
    @Override
    public Mono<Void> onAuthenticationFailure(WebFilterExchange webFilterExchange, AuthenticationException e) {
        ServerHttpResponse response = webFilterExchange.getExchange().getResponse();
        response.getHeaders().setContentType(MediaType.APPLICATION_JSON);
        ResultVO result = null;
        if (e instanceof UsernameNotFoundException) {
            //用户不存在
            result = new ResultVO<Void>().fail(ResultCode.USER_ACCOUNT_NOT_EXIST.getMessage());
        } else if (e instanceof BadCredentialsException) {
            // 密码错误
            result = new ResultVO<Void>().fail(ResultCode.USER_CREDENTIALS_ERROR.getMessage());
        } else {
            result = new ResultVO<Void>().fail();
        }

        DataBuffer buffer = response.bufferFactory().wrap(JSON.toJSONString(result).getBytes(StandardCharsets.UTF_8));
        return response.writeWith(Mono.just(buffer));
    }
}
